package com.jielihaofeng.nettyadvance.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author Johnnie Wind
 * @description 测试消息编解码
 * @date 2021/11/16 17:14
 */
public class TestMessageCodec {
    public static void main(String[] args) throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LoggingHandler(),
                // 帧解码器，解决黏包半包问题
                new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0),
                new MessageCodec()
        );

        // encode
        LoginRequestMessage message = new LoginRequestMessage("jielihaofeng", "123456");
//        channel.writeOutbound(message);

        // decode
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        new MessageCodec().encode(null, message, buf);
//        channel.writeInbound(buf);

        // 没有帧解码器，会出现半包黏包问题
        ByteBuf slice1 = buf.slice(0, 100);
        ByteBuf slice2 = buf.slice(100, buf.readableBytes() - 100);
        slice1.retain();
        // 没有帧解码器报错：java.lang.IndexOutOfBoundsException: readerIndex(16) + length(247) exceeds writerIndex(100): UnpooledSlicedByteBuf(ridx: 16, widx: 100, cap: 100/100, unwrapped: PooledUnsafeDirectByteBuf(ridx: 0, widx: 263, cap: 512))
        // 有帧解码器不报错
        channel.writeInbound(slice1);
        channel.writeInbound(slice2);
    }
}
